<?php

namespace app\logic\share;

use think\Exception;
use app\admin\model\share\Channel;
use app\admin\model\share\Template;
use app\admin\model\user\invite\Code AS UserInviteCode;

use app\logic\BaseLogic;

class InviteLogic extends BaseLogic
{

    /**
     * 获取分享链接
     *
     * @param integer $user_id
     * @param integer $creator_user_id
     * @return array
     */
    public function getShareLink(int $user_id, int $creator_user_id): array
    {
        $output = [];

        $invite_code = $this->getInviteCode($user_id, $creator_user_id);

        // 使用 leftJoin 将 Channel 和 Template 表关联
        $template_table = (new Template())->getTable();
        $template = Channel::alias('c')
                    ->leftJoin($template_table . ' t', 't.share_channel_id = c.id')
                    ->where('c.status', 1)
                    ->where('t.status', 1)
                    ->field('c.image, c.channel, t.*')
                    ->select()
                    ->toArray();

        if (empty($template)) {
            return $output;
        }

        $output = $template;
        foreach ($output as &$item) {
            $item['content'] = str_replace('{invite_code}', $invite_code, $item['content']);
        }

        return $output;
    }

    /**
     * 获取邀请码
     *
     * @param integer $user_id
     * @param integer $creator_user_id
     * @return string
     */
    public function getInviteCode(int $user_id, int $creator_user_id): string
    {
        // 找不到邀请码就创建一个invite_code
        // invite_code 是随机5位数，并且在表ba_user_invite_code里面是唯一值
        $invite_code = UserInviteCode::where('user_id', $user_id)->where('creator_user_id', $creator_user_id)->value('invite_code');
        if (empty($invite_code)) {
            // 尝试生成唯一的随机邀请码
            $maxRetries = 3000; // 最大重试次数
            $attempts = 0;
            do {
                $attempts++;
                $invite_code = mt_rand(1000000, 9999999);
        
                // 检查邀请码是否唯一
                $exists = UserInviteCode::where('invite_code', $invite_code)->find();
                if (!$exists) {
                    // 唯一值，直接插入
                    try {
                        UserInviteCode::create([
                            'user_id' => $user_id,
                            'creator_user_id' => $creator_user_id,
                            'invite_code' => $invite_code
                        ]);
                        break; // 插入成功，退出循环
                    } catch (Exception $e) {
                        // 捕获插入异常，继续重试
                        if ($attempts >= $maxRetries) {
                            throw new Exception('生成唯一邀请码失败：' . $e->getMessage());
                        }
                    }
                }
            } while ($attempts < $maxRetries);

            if ($attempts >= $maxRetries) {
                throw new Exception('生成唯一邀请码失败，达到最大重试次数');
            }
        }

        return $invite_code;
    }

}